package swing.admin.dao;

import swing.admin.model.User;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class UserDao extends BaseMapper<User> {


    public UserDao() {
        super(User.class);
    }

    public List<User> listAll() {
        List<User> list = selectList("select * from user", null);
        return list;
    }

    public List<User> list(User queryParam) {

        StringBuilder sql = new StringBuilder("select * from user where 1=1");
        ArrayList<Object> param = new ArrayList<>();

        if (!Objects.isNull(queryParam.getId())) {
            sql.append(" and id = ?");
            param.add(queryParam.getId());
        }

        if (!Objects.isNull(queryParam.getUsername())) {
            sql.append(" and username = ?");
            param.add(queryParam.getUsername());
        }

        if (!Objects.isNull(queryParam.getPassword())) {
            sql.append(" and password = ?");
            param.add(queryParam.getPassword());
        }

        System.out.println(sql);
        List<User> list = selectList(sql.toString(), param.toArray());
        return list;
    }

    public User getById(Integer id) {
        User user = selectOne("select * from user where id = ?", id);
        return user;
    }

    public void deleteById(Integer id) {
        boolean delete = delete("delete from user where id = ?", id);
    }

    public void updateById(User user){
        StringBuilder sql = new StringBuilder("update user");
        ArrayList<Object> param = new ArrayList<>();

        if (!Objects.isNull(user.getUsername())) {
            sql.append(" set username = ?");
            param.add(user.getUsername());
        }

        if (!Objects.isNull(user.getPassword())) {
            sql.append(", password = ?");
            param.add(user.getPassword());
        }

        if (!Objects.isNull(user.getId())) {
            sql.append(" where id = ?");
            param.add(user.getId());
        }

        System.out.println(sql);

        int update = update(sql.toString(), param.toArray());
        System.out.println(update);
    }

    public void insert(User user){
        ArrayList<Object> param = new ArrayList<>();
        param.add(user.getUsername());
        param.add(user.getPassword());
        boolean insert = insert("insert into user(username, password) values(?, ?)", param.toArray());
    }
}
